#
# NRK plugin for XBMC Media center
# Copyright (C) 2009 Victor Vikene  contact: z0py3r@hotmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#


import os
import log
import cPickle as pickle

class UnknownData( Exception ):
    pass
    
            
class BitBin:

    file_path = 'bitbin.dat' 
    
    _flag = None
    _bin  = dict()
           
           
    def __init__( self, file_path=None ):
        if file_path: self.file_path = file_path
        self._open()
        
    
    def write( self, key, data ):
        self._bin[key] = data
        self._flag = True
        
    
    def read( self, key ):
        if not self._bin.has_key( key ):
            raise UnknownData
        else:
            return self._bin[key]    
                       

    def _open( self ):
        if not os.path.isfile( self.file_path ):
            log.debug( 'No saved data. new data file created' )
            return None
            
        try:
            file_handle = open(self.file_path, 'rb')
            self._bin = pickle.load( file_handle )
            file_handle.close()
            
        except pickle.UnpicklingError:
            log.error( 'An error occured unpickling saved object' )
            return None

        else:
            log.debug( 'Read %s from disk to memory' % self.file_path )
            return True
            
                      
    def close( self ):
        if not self._flag:
            log.debug('No new data. No need for saving')
            return True
            
        log.debug('Write data to path "%s"' % self.file_path )
        
        if not os.path.isdir( os.path.dirname( self.file_path ) ):
            os.makedirs( os.path.dirname( self.file_path ) )
               
        try:
            file_handle = open( self.file_path, 'wb' )
            pickle.dump( self._bin, file_handle )
            file_handle.close()
            
        except pickle.PicklingError:
            log.error('An error occured during pickle dump')
            return None
            
        else: 
            self._flag = None
            return True
            
            
            
            
if ( __name__ == '__main__'):
    bitbin = BitBin()
    bitbin.file_path = os.path.join( os.getcwd(), 'bitbin.dat')
    bitbin.write('test', 'test')
    print bitbin.read('test')
    bitbin.close()
    
    